<template>
  <div class="search-dialog" v-if="dialogVisible">
    <el-dialog v-model="dialogVisible" title="搜索" width="500">
      <div class="search">
        <Search v-model:keyword="keyword" @handle-enter="handleKeyUp"></Search>
      </div>
      <div class="history">
        <div class="title">
          <div class="text">历史记录</div>
          <el-popconfirm
            title="您确定要清空历史记录吗?"
            width="240"
            confirm-button-text="是"
            cancel-button-text="否"
            @confirm="handleClear">
            <template #reference>
              <div class="btn">清空</div>
            </template>
          </el-popconfirm>
          <!-- <div class="btn" @click="handleClear">清空</div> -->
        </div>
        <div class="list" v-if="tags?.length > 0">
          <el-tag
            v-for="tag in tags"
            :key="tag"
            size="large"
            closable
            type="info"
            @click="handleClick(tag)"
            @close="handleClose(tag)">
            {{ tag }}
          </el-tag>
        </div>
        <div class="empty" v-else>暂无搜索记录</div>
      </div>
      <div class="result">
        <div class="title">搜索结果</div>
        <div class="list" v-if="list && list?.length > 0">
          <div class="item" v-for="item in list" :key="item.path" @click="handleClickResult(item)">
            <span>{{ item.name }}</span>
            <div class="type">{{ item.type }}</div>
          </div>
        </div>
        <div class="empty" v-else>暂无搜索记录</div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import Search from "./Search.vue";
import { onMounted, onUnmounted, Ref, ref } from "vue";
import { useAllFiles } from "@/store/allFiles";
import { allFilesNameAndPathItemType } from "@/store/allFiles.type";
import { useRouter } from "vue-router";
import { useMenu } from "@/store/menu";
const store = useMenu();
const router = useRouter(); // 获取路由实例

const fileStore = useAllFiles();
let dialogVisible = ref(false);
const setShow = (value: boolean) => {
  dialogVisible.value = value;
};
// 注册全局方法
window.$setSearchDialog = setShow;

// 添加键盘事件监听器
const handleKeyDown = (event: KeyboardEvent) => {
  if (event.ctrlKey && event.key === "k") {
    event.preventDefault();
    setShow(!dialogVisible.value); // 显示弹窗
  }
};

onMounted(() => {
  // 监听键盘事件
  window.addEventListener("keydown", handleKeyDown);
});
onUnmounted(() => {
  window.removeEventListener("keydown", handleKeyDown);
});
const getState = () => {
  return dialogVisible.value;
};

defineExpose({ setShow, getState });
// 搜索关键字
let keyword = ref("");
// 历史记录
let tags = ref<string[]>([]);
const getTags = () => {
  let data = localStorage.getItem("tags");
  if (data) {
    tags = ref(JSON.parse(data));
  } else {
    tags = ref([]);
  }
};
getTags();

// 回车搜索
const handleKeyUp = (e: Ref) => {
  // 执行搜索
  handleSearch(e.value);
};

// 点击历史记录搜索
const handleClick = (e: string) => {
  // 执行搜索
  handleSearch(e);
};

let list = ref<allFilesNameAndPathItemType[]>();
// 搜索
const handleSearch = (e: string) => {
  if (!e) {
    return;
  }
  let data = [...tags.value];
  data.indexOf(e) !== -1 && data.splice(data.indexOf(e), 1);
  data.unshift(e);
  keyword.value = "";
  data.splice(10);
  tags = ref(data);
  localStorage.setItem("tags", JSON.stringify(tags.value));
  list.value = fileStore.searchFileByName({ name: e, root: true });
};

// 单个删除
const handleClose = (tag: string) => {
  tags.value.splice(tags.value.indexOf(tag), 1);
  localStorage.setItem("tags", JSON.stringify(tags.value));
};

// 全部清空
const handleClear = () => {
  tags.value = [];
  localStorage.setItem("tags", JSON.stringify(tags.value));
};

// 点击结果
const handleClickResult = (item: allFilesNameAndPathItemType) => {
  dialogVisible.value = false;
  if (item.type === "html") {
    store.$state.activeName = "component";
    store.$state.defaultActive = "/component/html";
    store.$state.isRouter = true;
    router
      .push({
        name: "html-details",
        query: { base: item.base },
      })
      .then(() => {
        store.handleChange("component", false);
      });
  } else if (item.type === "vue2") {
    store.$state.activeName = "component";
    store.$state.defaultActive = "/component/vue2";
    store.$state.isRouter = true;
    router
      .push({
        name: "vue2-details",
        query: { info: JSON.stringify(item) },
      })
      .then(() => {
        store.handleChange("component", false);
      });
  } else if (item.type === "vue3") {
    store.$state.activeName = "component";
    store.$state.defaultActive = "/component/vue3";
    store.$state.isRouter = true;
    router
      .push({
        name: "vue3-details",
        query: { info: JSON.stringify(item) },
      })
      .then(() => {
        store.handleChange("component", false);
      });
  } else if (item.type === "javascript") {
    store.$state.activeName = "javascripts";
    store.$state.isRouter = false;
    router
      .push({
        name: "jsDetails",
        query: { activeKey: item.path },
      })
      .then(() => {
        store.handleChange("javascripts", false);
      });
  } else if (item.type === "markdown") {
    store.$state.activeName = "markdowns";
    store.$state.isRouter = false;
    router
      .push({
        name: "MarkDownDetails",
        query: { activeKey: item.path },
      })
      .then(() => {
        store.handleChange("markdowns", false);
      });
  }
};
</script>

<style lang="scss" scoped>
.search-dialog {
  position: fixed;
  top: 0;
  margin: 0;
  padding: 0;
  width: 100vw;
  height: 100vh;
  z-index: 2000;

  :deep(.el-overlay) .el-dialog {
    background-color: #eee;
  }

  .search {
    padding: 10px 30px;
    box-sizing: border-box;
  }

  .history {
    .title {
      display: flex;
      align-items: center;
      justify-content: space-between;
      font-weight: 900;

      .btn {
        cursor: pointer;
      }
    }

    .list {
      display: flex;
      flex-wrap: wrap;
      gap: 10px;
      padding: 10px 0;
      box-sizing: border-box;

      :deep(.el-tag) {
        cursor: pointer;

        &:hover {
          transform: scale(1.2);
        }
      }
    }
  }

  .result {
    .title {
      font-weight: 900;
    }
    .list {
      margin-top: 10px;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      gap: 10px;
      .item {
        cursor: pointer;
        width: 100%;
        line-height: 40px;
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 0 20px;
        box-sizing: border-box;
        box-shadow: 5px 5px 10px #ccc;
        border-radius: 10px;
      }
    }
  }

  .empty {
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 20px 0;
  }
}
</style>
